﻿using System.Web.Mvc;
using ECatalog.Models.UserIU;
using ECatalog.Models.UserModel;

namespace ECatalog.Controllers
{
    public class BaseController : Controller
    {
        private readonly IUserRepository userRepository;
        private readonly IBuilder builder;

        public BaseController(IUserRepository userRepository, IBuilder builder)
        {
            this.userRepository = userRepository;
            this.builder = builder;
        }

        public ActionResult Index()
        {
            var isAdmin = userRepository.IsAdmin(User.Identity.Name);
            @ViewBag.IsAdmin = isAdmin;
            if (isAdmin)
            {
                return View("Index");
            }
            @ViewBag.ErrorMessage = "";
            var mainViewModel = builder.BuildViewModel();
            return View("UserUI",mainViewModel);
        }
        
        public ActionResult GetComplects(int organizationId, string numModel)
        {
            var modelAndComplectsViewModel = builder.BuildComplectsViewModel(organizationId,numModel);
            if (modelAndComplectsViewModel == null)
            {
                @ViewBag.ErrorMessage = "Модель не найдена";
                var mainViewModel = builder.BuildViewModel();
                return View("UserUI", mainViewModel);
            }
            return View("UserUIModelAndComplects", modelAndComplectsViewModel);
        }
        
        [HttpPost]
        public JsonResult GetComplectsJson(GetComplectsParams getComplectsParams)
        {
            var complectsDto = builder.BuildComplectsDto(getComplectsParams.OrganizationId, getComplectsParams.NumModel);
            if (complectsDto != null)
            {
                return Json(complectsDto);
            }
            return Json("error");
        }
    }
}
